package com.sugon.api;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.cait.bpmsuite.api.bpmmodle.BPMWorkItem;
import com.sugon.annotation.AuthCheck;
import com.sugon.annotation.AutoLog;
import com.sugon.annotation.LimitSubmit;
import com.sugon.annotation.LoginUser;
import com.sugon.dao.DevRepairRecordDao;
import com.sugon.dao.MaterialBaseDao;
import com.sugon.dao.MaterialRecordDao;
import com.sugon.entity.*;
import com.sugon.entity.dto.MaterialEaData;
import com.sugon.entity.dto.PickListDTO;
import com.sugon.entity.vo.SpareMaterialBaseApproveParam;
import com.sugon.modules.base.consts.BusModule;
import com.sugon.modules.base.consts.MaterialBaseType;
import com.sugon.modules.sparepart.consts.MaterialBaseConst;
import com.sugon.modules.sparepart.consts.MaterialBaseProgress;
import com.sugon.modules.sparepart.model.vo.CommonApproveParamVO;
import com.sugon.modules.sparepart.model.vo.SparepartMaterialItemParam;
import com.sugon.modules.sparepart.service.ISparepartManager;
import com.sugon.modules.sparepart.service.ISparepartMaterialBaseManager;
import com.sugon.modules.workflow.IWorkFlowManager;
import com.sugon.modules.workflow.consts.ProcessState;
import com.sugon.service.*;
import com.sugon.util.ApiBaseAction;
import com.sugon.utils.Constant;
import com.sugon.utils.PageUtils;
import com.sugon.utils.Query;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api(tags = "备件业务API,包含备件查询、库存查询、创建领料单等所有备件相关")
@RestController
@RequestMapping("/api/v1/spareParts")
public class SparePartsBusinessApiController extends ApiBaseAction {

    @Autowired
    private ISparepartManager sparepartManager;
    @Autowired
    private SparePartService sparePartService;
    @Autowired
    private MaterialBaseService materialBaseService;
    @Autowired
    private MaterialRecordService materialRecordService;
    @Autowired
    private SpareStorePosService spareStorePosService;
    @Autowired
    private ToolsStorePosService toolsStorePosService;
    @Autowired
    private ISparepartMaterialBaseManager sparepartMaterialBaseManager;
    @Autowired
    private SysUserService userService;
    @Autowired
    private SpareDevService spareDevService;
    @Autowired
    private SparePartTransactionRecordService sparePartTransactionRecordService;
    @Resource
    private IWorkFlowManager workFlowManager;
    @Resource
    private MaterialBaseDao materialBaseDao;
    @Resource
    private MaterialRecordDao materialRecordDao;
    @Resource
    private SysOaProcessService oaProcessService;
    @Resource
    private DevRepairRecordDao repairRecordDao;

    @AutoLog(value = "移动端查询备件", busModule = BusModule.SPARE_PARTS)
    @AuthCheck
    @ApiOperation(value = "备件查询API")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Id", value = "备件ID", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "partCode", value = "备件编码", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "producor", value = "厂家名称", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "spec", value = "规格", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "erpCode", value = "备件ERP编码", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "partName", value = "备件名称", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "status", value = "审批状态", paramType = "query", dataType = "int"),
            @ApiImplicitParam(name = "page", value = "当前页码", paramType = "query", dataType = "int", required = true),
            @ApiImplicitParam(name = "limit", value = "每页记录数", paramType = "query", dataType = "int", required = true)
    })
    @PostMapping
    public ApiResult<PageUtils> querySpareParts(@ApiIgnore @RequestParam Map<String, Object> params) {
        ApiResult<PageUtils> apiResult = new ApiResult<>();
        return apiResult.success(sparepartManager.querySpareParts(params));
    }

    /**
     * 备件详情查询API
     *
     * @param sparePartId
     * @return
     */
    @AuthCheck
    @ApiOperation(value = "备件详情查询API")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "sparePartId", value = "备件ID", paramType = "path", dataType = "String", required = true),
    })
    @PostMapping("/info/{sparePartId}")
    public ApiResult<SparePartEntity> info(@PathVariable("sparePartId") String sparePartId) {
        ApiResult<SparePartEntity> apiResult = new ApiResult<>();
        return apiResult.success(sparePartService.queryObject(sparePartId));
    }

    /**
     * 备件库存查询API
     *
     * @param params
     * @return
     * @throws Exception
     */
    @AutoLog(value = "移动端查询备件库存", busModule = BusModule.SPARE_PARTS)
    @AuthCheck
    @ApiOperation(value = "备件库存查询API")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Id", value = "备件ID", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "lowestNum", value = "库存数最小值，只返回>=该库存数的库存记录", paramType = "query", dataType = "int"),
            @ApiImplicitParam(name = "partCode", value = "备件编码", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "producor", value = "厂家名称", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "spec", value = "规格", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "erpCode", value = "备件ERP编码", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "partName", value = "备件名称", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "status", value = "审批状态", paramType = "query", dataType = "int"),
            @ApiImplicitParam(name = "page", value = "当前页码", paramType = "query", dataType = "int", required = true),
            @ApiImplicitParam(name = "limit", value = "每页记录数", paramType = "query", dataType = "int", required = true)
    })
    @PostMapping("/stock")
    public ApiResult<PageUtils> querySparePartsStock(@ApiIgnore @RequestParam Map<String, Object> params) throws Exception {
        ApiResult<PageUtils> apiResult = new ApiResult<>();
        List<String> matchedSparepartIdList = null;
        // 只要是map中含有任意一个备件查询参数，那么需要查询关联
        Map<String, Object> filterParams = cn.hutool.core.map.MapUtil.getAny(params, "partName", "spec", "partCode", "erpCode", "producor");
        if (cn.hutool.core.map.MapUtil.isNotEmpty(filterParams)) {
            matchedSparepartIdList = spareDevService.getMatchedSparePartIdList(params);
            if (CollectionUtil.isEmpty(matchedSparepartIdList)) {
                return apiResult.success(new PageUtils(new ArrayList<>(), 0, cn.hutool.core.map.MapUtil.getInt(params, "limit"), MapUtil.getInt(params, "page")));
            } else {
                // 如果根据搜索条件搜索出来的内容超过500，提示筛选搜索
                if (matchedSparepartIdList.size() > 500) {
                    return apiResult.failMsg("匹配当前查询条件的记录数过多，请进一步细化查询条件！");
                }
                params.put("sparepartIdList", matchedSparepartIdList);
            }
        }
        return apiResult.success(sparepartManager.querySparePartsStock(params));
    }

    /**
     * 备件领料单查询API
     *
     * @param params
     * @return
     */
    @AutoLog(value = "移动端查询备件领料单", busModule = BusModule.LLD)
    @AuthCheck
    @ApiOperation(value = "备件领料单查询API")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "materCode", value = "领料单编号", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "jobCode", value = "工单编号", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "progress", value = "领料单状态", paramType = "query", dataType = "int"),
            @ApiImplicitParam(name = "picker", value = "领料人", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "page", value = "当前页码", paramType = "query", dataType = "int", required = true),
            @ApiImplicitParam(name = "limit", value = "每页记录数", paramType = "query", dataType = "int", required = true)
    })
    @PostMapping("/materialList")
    public ApiResult<PageUtils> querySparePartsMaterialListDetail(@ApiIgnore @RequestParam Map<String, Object> params) {
        ApiResult<PageUtils> apiResult = new ApiResult<>();
        //查询列表数据
        Query query = new Query(params);
        List<MaterialBaseEntity> materialBaseList = materialBaseService.queryList(query);
        int total = materialBaseService.queryTotal(query);
        return apiResult.success(new PageUtils(materialBaseList, total, query.getLimit(), query.getPage()));
    }

    /**
     * 备件领料单详情查询API
     *
     * @param materialListId
     * @return
     */
    @AutoLog(value = "移动端查询备件领料单详情", busModule = BusModule.LLD)
    @AuthCheck
    @ApiOperation(value = "备件领料单详情查询API")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "materialListId", value = "领料单ID", paramType = "path", dataType = "String", required = true),
    })
    @PostMapping("/materialList/{materialListId}/detail")
    public ApiResult<MaterialBaseEntity> querySparePartsMaterialListDetail(@PathVariable("materialListId") String materialListId) {
        ApiResult<MaterialBaseEntity> apiResult = new ApiResult<>();

        Map<String, Object> params = new HashMap<>();
        params.put("page", 1);
        params.put("limit", 100);
        params.put("Id", materialListId);
        //查询列表数据
        Query query = new Query(params);
        List<MaterialBaseEntity> materialBaseList = materialBaseService.queryList(query);
        if (CollectionUtil.isNotEmpty(materialBaseList)) {
            return apiResult.success(materialBaseList.get(0));
        } else {
            return apiResult.failMsg("领料单不存在，请确认！");
        }
    }

    /**
     * 备件领料单明细查询API
     *
     * @param materialListId
     * @return
     */
    @AutoLog(value = "移动端查询备件领料单明细", busModule = BusModule.LLD)
    @AuthCheck
    @ApiOperation(value = "备件领料单明细查询API")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "materialListId", value = "领料单ID", paramType = "path", dataType = "String", required = true),
    })
    @PostMapping("/materialList/{materialListId}/items")
    public ApiResult<List<MaterialRecordEntity>> querySparePartsMaterialListItems(@PathVariable("materialListId") String materialListId) {
        ApiResult<List<MaterialRecordEntity>> apiResult = new ApiResult<>();
        Map<String, Object> params = new HashMap<>();
        params.put("page", 1);
        params.put("limit", 1000);
        params.put("material", materialListId);
        //查询列表数据
        Query query = new Query(params);
        return apiResult.success(materialRecordService.queryList(query));
    }

    @AutoLog(value = "移动端查询备件领料单审批记录", busModule = BusModule.LLD)
    @AuthCheck
    @ApiOperation(value = "查询备件领料单审批记录API")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "busType", value = "业务类型", paramType = "query", dataType = "String", required = true),
            @ApiImplicitParam(name = "busId", value = "业务ID", paramType = "query", dataType = "String", required = true)
    })
    @PostMapping("/materialList/oaProcess")
    public ApiResult<List<SysOaProcessEntity>> queryOaProcess(@RequestParam String busType, @RequestParam String busId) {
        ApiResult<List<SysOaProcessEntity>> apiResult = new ApiResult<>();
        Map<String, Object> params = new HashMap<>();
        params.put("busType", busType);
        params.put("busId", busId);
        return apiResult.success(oaProcessService.queryList(params));
    }

    @AuthCheck
    @ApiOperation(value = "更新备件图片API")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "备件ID", paramType = "query", dataType = "string", required = true),
            @ApiImplicitParam(name = "reserve2", value = "备件图片地址", paramType = "query", dataType = "string", required = true)
    })
    @PostMapping("/updateSpPicture")
    public ApiResult<String> updateSpPicture(@ApiIgnore @LoginUser SysUserEntity loginUser, @ApiIgnore SparePartEntity sp) {
        ApiResult<String> apiResult = new ApiResult<>();
        // 备件ID和备件图片地址必填
        if (!ObjectUtil.isAllNotEmpty(sp.getId(), sp.getReserve2())) {
            return apiResult.failMsg("备件ID和图片必填！");
        }
        // 校验备件是否存在
        SparePartEntity existedSp = sparePartService.queryObject(sp.getId());
        if (existedSp == null) {
            return apiResult.failMsg("备件不存在，请确认！");
        }
        existedSp.setReserve2(sp.getReserve2());
        return sparePartService.update(existedSp) > 0 ? apiResult.success() : apiResult.failMsg("更新失败，请稍后重试！");
    }

    /**
     * 新增领料单API
     *
     * @param loginUser
     * @param materialBase
     * @return
     * @throws Exception
     */
    @AutoLog(value = "移动端新增领料单", busModule = BusModule.LLD)
    @AuthCheck
    @ApiOperation(value = "新增领料单API", notes = "领料单分为线边库(materialType=1)和维修领料(materialType=2两种")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "materialType", value = "领料类别", paramType = "query", dataType = "int", required = true, allowableValues = "1,2"),
            @ApiImplicitParam(name = "purpose", value = "用途", paramType = "query", dataType = "String", required = true),
            @ApiImplicitParam(name = "jobCode", value = "维修工单编号", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "lineCode", value = "产线编码", paramType = "query", dataType = "int"),
            @ApiImplicitParam(name = "remark", value = "备注", paramType = "query", dataType = "int")
    })
    @PostMapping("/addMaterialList")
    public ApiResult<PageUtils> addMaterialList(@ApiIgnore @LoginUser SysUserEntity loginUser, @ApiIgnore MaterialBaseEntity materialBase) throws Exception {
        // 本接口默认备件领料
        materialBase.setType(0);
        ApiResult<PageUtils> apiResult = new ApiResult<>();
        Integer materialType = materialBase.getMaterialType();
        // 如果是维修领料的话，需要做以下校验并关联产线
        if (MaterialBaseConst.REPAIR_MATERIAL.equals(materialType)) {
            // 维修工单号必填
            String jobCode = materialBase.getJobCode();
            if (StrUtil.isEmpty(jobCode)) {
                return apiResult.failMsg("维修领料时维修工单号必填！");
            }
            // 校验维修记录是否存在
            DevRepairRecordEntity repairRecord = repairRecordDao.queryObjectByCode(jobCode);
            if (repairRecord == null) {
                return apiResult.failMsg("非法维修工单编号！");
            }
            materialBase.setLineCode(repairRecord.getDevProductCode());
        } else if (MaterialBaseConst.COMMON_MATERIAL.equals(materialType)) {
            if (StrUtil.isEmpty(materialBase.getLineCode())) {
                return apiResult.failMsg("日常领料时，必须录入领用的生产线！");
            }
        }
        materialBase.setPicker(loginUser.getUserId());
        String deptId = loginUser.getDeptId();
        if (StrUtil.isNotEmpty(deptId) && deptId.length() >= 4) {
            materialBase.setDeptId(deptId.substring(0, 4));
        }
        return materialBaseService.save(materialBase) > 0 ? apiResult.succMsg("创建成功") : apiResult.failMsg("新增领料单失败");
    }

    /**
     * 新增领料单明细API
     *
     * @param loginUser
     * @param materialRecord
     * @return
     */
    @AutoLog(value = "移动端新增领料单明细", busModule = BusModule.LLD)
    @AuthCheck
    @ApiOperation(value = "新增领料单明细API")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "material", value = "领料单ID", paramType = "query", dataType = "String", required = true),
            @ApiImplicitParam(name = "postionId", value = "库位ID", paramType = "query", dataType = "String", required = true),
            @ApiImplicitParam(name = "num", value = "领用数量", paramType = "query", dataType = "int", required = true),
            @ApiImplicitParam(name = "spareCode", value = "备件编码", paramType = "query", dataType = "String", required = true)
    })
    @PostMapping("/addMaterialListItem")
    public ApiResult<String> save(@ApiIgnore @LoginUser SysUserEntity loginUser, @ApiIgnore MaterialRecordEntity materialRecord) {
        ApiResult<String> apiResult = new ApiResult<>();
        // 领用数不得小于1
        int num = materialRecord.getNum();
        if (num < 1) {
            return apiResult.failMsg("备件领用数量不得小于1");
        }
        // 获取领料单ID
        String materialBaseId = materialRecord.getMaterial();
        MaterialBaseEntity materialBase = materialBaseService.queryObject(materialBaseId);
        if (materialBase == null) {
            return apiResult.failMsg("领料单不存在,请确认！");
        }
        // 根据领料单类别对对应库存实施锁定
        int type = materialBase.getType();
        if (type == MaterialBaseType.SPARE_PART) {
            // 校验库位是否存在
            SpareStorePosEntity spareStorePos = spareStorePosService.queryObject(materialRecord.getPostionId());
            if (spareStorePos == null) {
                return apiResult.failMsg("库位不存在，请确认");
            }
            // 校验可用库存是否可用
            int curStoreNum = spareStorePos.getStoreNum();
            int curLocNum = spareStorePos.getLocNum();
            if (curStoreNum - curLocNum < num) {
                return apiResult.failMsg("可领用库存不足，请更换！");
            }
            // 设置仓库ID和库位编码
            materialRecord.setStore(spareStorePos.getStoreId());
            materialRecord.setPostion(spareStorePos.getPostion());
            // 设置备件名称
            SparePartEntity sparePartEntity = sparePartService.queryByCode(spareStorePos.getSpareCode());
            if (sparePartEntity == null) {
                return apiResult.failMsg("备件信息不存在，请确认！");
            }
            materialRecord.setSpareName(sparePartEntity.getName());
        } else if (type == MaterialBaseType.TOOLS) {
            // 校验库位是否存在
            ToolsStorePosEntity toolsStorePos = toolsStorePosService.queryObject(materialRecord.getPostionId());
            if (toolsStorePos == null) {
                return apiResult.failMsg("库位不存在，请确认");
            }
            // 校验可用库存是否可用
            int curStoreNum = toolsStorePos.getStoreNum();
            int curLocNum = toolsStorePos.getLocNum();
            if (curStoreNum - curLocNum < num) {
                return apiResult.failMsg("可领用库存不足，请更换！");
            }
        }
        // 保存领料单详情
        int rows = materialRecordService.add(materialRecord);
        if (rows > 0) {
            // 根据领料单类别对对应库存实施锁定
            String positionId = materialRecord.getPostionId();
            if (type == MaterialBaseType.SPARE_PART) {
                spareStorePosService.lockStockNum(positionId, num);
            } else if (type == MaterialBaseType.TOOLS) {
                toolsStorePosService.lockStockNum(positionId, num);
            }
            return apiResult.success();
        } else {
            return apiResult.fail();
        }
    }

    /**
     * 提交领料单审核API
     *
     * @param approveParam
     * @param bindingResult
     * @return
     */
    @AutoLog(value = "移动端提交领料单审核", busModule = BusModule.LLD)
    @AuthCheck
    @ApiOperation(value = "提交领料单审核API")
    @ApiImplicitParam(name = "id", value = "领料单ID", paramType = "path", dataType = "String", required = true)
    @PostMapping("/commitApprove")
    public ApiResult<String> commitApprove(@Validated @RequestBody SpareMaterialBaseApproveParam approveParam, BindingResult bindingResult) {
        // 常规校验
        ApiResult<String> apiResult = getValidApiResult(bindingResult);
        if (apiResult != null) {
            return apiResult;
        }
        apiResult = new ApiResult<>();
        MaterialBaseEntity materialBase = materialBaseService.queryObject(approveParam.getId());
        // 校验领料单是否存在
        if (materialBase == null) {
            return apiResult.failMsg("领料单不存在,请确认!");
        }
        // 只有新建工单才可以提交审核
        if (materialBase.getProgress() != MaterialBaseProgress.NEW && materialBase.getProgress() != MaterialBaseProgress.NOT_PASSED) {
            return apiResult.failMsg("只有新建工单才可以提交审核!");
        }
        // 校验下是否已添加备件
        List<MaterialRecordEntity> materialRecords = materialRecordService.queryByMater(approveParam.getId());
        if (CollectionUtil.isEmpty(materialRecords)) {
            return apiResult.failMsg("请在领料单添加备件后再提交审核!");
        }
        // 校验审批人是否存在
        SysUserEntity user = userService.queryObject(approveParam.getApproverId());
        if (user == null) {
            return apiResult.failMsg("审批用户不存在，请确认!");
        }
        materialBase.setApproverUser(user);
        // 设置室主任审批人:这个ID是长安认证中心的用户ID
        materialBase.setApproverUnionId(user.getUnionId());
        return sparepartMaterialBaseManager.commitApprove(materialBase) ? apiResult.success() : apiResult.failMsg("提交审核失败！");
    }

    @AutoLog(value = "移动端查询备件事务明细", busModule = BusModule.SPARE_PARTS)
    @AuthCheck
    @ApiOperation(value = "查询备件事务明细API")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "sparePartId", value = "备件ID", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "page", value = "当前页码", paramType = "query", dataType = "int", required = true),
            @ApiImplicitParam(name = "limit", value = "每页记录数", paramType = "query", dataType = "int", required = true)
    })
    @PostMapping("/transactionItem")
    public ApiResult<PageUtils> queryTransactionItem(@ApiIgnore @RequestParam Map<String, Object> params) {
        ApiResult<PageUtils> apiResult = new ApiResult<>();
        //查询列表数据
        Query query = new Query(params);
        List<SparePartTransactionRecordEntity> sparePartTransactionRecordList = sparePartTransactionRecordService.queryList(query);
        int total = sparePartTransactionRecordService.queryTotal(query);
        return apiResult.success(new PageUtils(sparePartTransactionRecordList, total, query.getLimit(), query.getPage()));
    }


    /**
     * 查看信息,两部分
     * 1、当前审核的进度
     * 2、领料单列表
     */

    /**
     * @param procInstId
     * @param workItemId
     * @return
     */
    @AuthCheck
    @ApiOperation(value = "查询备件领料移动端审批需要的审批数据API")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "procInstId", value = "流程实例ID", paramType = "query", dataType = "string"),
            @ApiImplicitParam(name = "workItemId", value = "工作项ID", paramType = "query", dataType = "string")
    })
    @PostMapping("/loadSpareMaterialBaseList")
    public ApiResult<MaterialEaData> loadSpareMaterialBaseList(@RequestParam(value = "procInstId", required = false) String procInstId, @RequestParam(value = "workItemId", required = false) String workItemId) {
        ApiResult<MaterialEaData> apiResult = new ApiResult<>();
        // 流程实例或流程工作审批项 必填其一
        if (StrUtil.isAllBlank(procInstId, workItemId)) {
            return apiResult.failMsg("流程实例或流程工作审批项必填其一！");
        }
        MaterialEaData eaData = new MaterialEaData();
        /*
            以下做两个事情：
            1、如果流程实例ID为指定，那么从工作项中获取
            2、设置当前人员是否可以处理该审批工作项
         */
        Integer workItemState = ProcessState.COMPLETED;
        // 如果流程实例ID为指定，那么从工作项中获取
        if (StrUtil.isEmpty(procInstId)) {
            BPMWorkItem workItem = workFlowManager.getWorkItemById(workItemId);
            if (workItem == null) {
                return apiResult.failMsg("流程工作审批项不存在，请确认！");
            }
            procInstId = workItem.getProcInstId();
            // 获取工作项状态
            workItemState = workItem.getState();
            eaData.setWorkItem(workItem);
        }
        if (NumberUtil.equals(ProcessState.ING, workItemState)) {
            eaData.setIsShow(1);
        }
        // 获取并设置OA审批记录
        List<SysOaProcessEntity> auditRecordList = materialBaseDao.queryAuditRecordByProcInstId(procInstId);
        if (CollectionUtil.isNotEmpty(auditRecordList)) {
            eaData.setEaRecords(auditRecordList);
        }
        // 根据流程实例获取领料单信息
        PickListDTO pickListDTO = materialBaseDao.queryPickListByProcInstId(procInstId);
        if (pickListDTO != null) {
            // 设置领料明细
            if (CollectionUtil.isNotEmpty(pickListDTO.getMaterialItems())) {
                eaData.setMaterialItems(pickListDTO.getMaterialItems());
            }
        } else {
            pickListDTO = new PickListDTO();
            pickListDTO.setId("");
            pickListDTO.setPickerName("");
            pickListDTO.setDeptName("");
            pickListDTO.setPurpose("");
            pickListDTO.setPickDate(DateUtil.date());
        }
        // 设置领料单信息
        eaData.setApplyInfo(pickListDTO);
        return apiResult.success(eaData);
    }

    @AuthCheck
    @ApiOperation(value = "移动端更改实发数API")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "领料明细ID", paramType = "query", dataType = "string"),
            @ApiImplicitParam(name = "actualNum", value = "工作项ID", paramType = "query", dataType = "string")
    })
    @PostMapping("/updateActualNum")
    public ApiResult<String> updateActualNum(@Validated SparepartMaterialItemParam param, BindingResult bindingResult) {
        // 常规校验
        ApiResult<String> apiResult = getValidApiResult(bindingResult);
        if (apiResult != null) {
            return apiResult;
        }
        apiResult = new ApiResult<>();

        // 校验领用明细ID是否合法
        MaterialRecordEntity entity = materialRecordService.queryObject(param.getId());
        if (entity == null) {
            return apiResult.failMsg("非法领用明细ID！");
        }
        // 实发数不得大于申请数
        if (param.getActualNum() > entity.getNum()) {
            return apiResult.failMsg("实发数不得大于申请数！");
        }
        entity.setActualNum(param.getActualNum());
        return materialRecordService.update(entity) > 0 ? apiResult.success("调整实发数成功！") : apiResult.failMsg("调整实发数失败，请稍后重试！");
    }

    @AuthCheck
    @ApiOperation(value = "移动端删除领料明细API", notes = "逻辑删除")
    @ApiImplicitParam(name = "id", value = "领料明细ID", paramType = "query", dataType = "string")
    @PostMapping("/logicDelete")
    public ApiResult<String> logicDelete(@RequestParam String itemId) {
        ApiResult<String> apiResult = new ApiResult<>();
        // 查看当前领料明细所在的领料单 只要保留一条记录
        List<MaterialRecordEntity> itemList = materialRecordDao.listAllBaseItem(itemId);
        if (CollectionUtil.isEmpty(itemList) || itemList.size() < 2) {
            return apiResult.failMsg("删除失败，请确保备件领用申请列表中至少包含一条申请记录！");
        }
        // 逻辑删除指的是将delFlag字段置为空
        MaterialRecordEntity param = new MaterialRecordEntity();
        param.setId(itemId);
        param.setDelFlag(Constant.IS_DEL_INT);
        return materialRecordService.update(param) > 0 ? apiResult.success("删除成功！") : apiResult.failMsg("删除失败，请稍后重试！");
    }

    /**
     * 审核处理
     */
    @LimitSubmit(key = "spareMaterCheck:%s")
    @AuthCheck
    @ApiOperation(value = "移动端审核领料API")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "领料单ID", paramType = "form", dataType = "string", required = true),
            @ApiImplicitParam(name = "workItemId", value = "流程工作项ID", paramType = "form", dataType = "string", required = true),
            @ApiImplicitParam(name = "state", value = "审核状态，1:审批通过 2:审批不通过", paramType = "form", allowableValues = "1,2", dataType = "string", required = true),
            @ApiImplicitParam(name = "workshopApproverId", value = "申请单位领导ID，ERMS系统用户ID。[2.申请单位业务主管审核]时必填", paramType = "form", dataType = "string"),
            @ApiImplicitParam(name = "checkRemark", value = "审批意见", paramType = "form", dataType = "string")
    })
    @PostMapping("/check")
    public ApiResult<String> check(@ApiIgnore @LoginUser SysUserEntity loginUser, @Validated CommonApproveParamVO approveParam, BindingResult bindingResult) {
        // 常规校验
        ApiResult<String> apiResult = getValidApiResult(bindingResult);
        if (apiResult != null) {
            return apiResult;
        }
        apiResult = new ApiResult<>();

        // 设置当前审批人
        approveParam.setApprover(loginUser.getUserId());

        // 校验流程审批工作项是否存在
        String workItemId = approveParam.getWorkItemId();
        BPMWorkItem workItem = workFlowManager.getWorkItemById(workItemId);
        if (workItem == null) {
            return apiResult.failMsg("流程审批工作项不存在，请确认！");
        }
        approveParam.setBpmWorkItem(workItem);
        // 2.申请单位业务主管审核且审批通过时 必须指定 申请单位领导
        if (StrUtil.contains(workItem.getName(), "申请单位业务主管审核") && NumberUtil.equals(1, approveParam.getState())) {
            // 必须指定 申请单位领导
            String workshopApproverId = approveParam.getWorkshopApproverId();
            if (StrUtil.isEmpty(workshopApproverId)) {
                return apiResult.failMsg("申请单位业务主管审核时，必须指定[申请单位领导]！");
            }
            // 校验是否是系统用户
            SysUserEntity ermsUser = userService.queryObject(workshopApproverId);
            if (ermsUser == null) {
                return apiResult.failMsg("您指定的[申请单位领导]不是ERMS系统用户，请联系管理员进行添加！");
            }
            // 校验是否登陆过系统
            if (StrUtil.isEmpty(ermsUser.getUnionId())) {
                return apiResult.failMsg("您指定的[申请单位领导]尚未登陆过ERMS系统，不能作为下一级审批人！");
            }
            approveParam.setWorkshopApprover(ermsUser.getUnionId());
        }
        // 获取领料单ID
        String id = approveParam.getId();
        // 校验下是否已添加备件
        List<MaterialRecordEntity> materialRecords = materialRecordService.queryByMater(id);
        Assert.notEmpty(materialRecords);
        // 简单校验：校验该工作项是否已审核，如果已审核，那么根据审核情形，跳转到不同页面
        SysOaProcessEntity handledWorkItem = oaProcessService.queryByProcessWorkItemId(workItemId);
        if (handledWorkItem == null) {
            sparepartMaterialBaseManager.check(approveParam);
        }
        return apiResult.success();
    }

}
